﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using WTAppletProjectHTTPS.Models;

namespace WTAppletProjectHTTPS.Controllers
{
    [JwtAuthentication]
    public class LaserMarkingStationSelfInspectionConfirmationController : ApiController
    {
        private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
        // POST api/<controller>
        public async Task<HttpResponseMessage> Post([FromBody] LaserMarkingStationSelfInspectionConfirmation LMSSIC)
        {
            ReturnObject RO = new ReturnObject();
            if (LMSSIC == null ||
                string.IsNullOrEmpty(LMSSIC.LMSSIC_OperatorName) ||
                string.IsNullOrEmpty(LMSSIC.LMSSIC_LineParting))
            {
                Logger.Warn("输入值无效");
                RO.Status = HttpStatusCode.BadRequest;
                RO.Message = "输入值无效";
                RO.Data = null;
                return Request.CreateResponse(HttpStatusCode.BadRequest, RO);
            }

            using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString))
            {
                connection.Open();
                using (var transaction = connection.BeginTransaction())
                {
                    try
                    {
                        var query = @"INSERT INTO LaserMarkingStationSelfInspectionConfirmation 
                                    (LMSSCOperatorName, LMSSCConfirmationTime, LMSSCLineParting, LMSSCProductVSMarkingModel, 
                                     LMSSCNonconformanceDescriptionIfAny,LMSSCNonconformanceImage,LMSSCCreateCreator,LMSSCCreateTime)
                                    VALUES 
                                    (@OperatorName, @ConfirmationTime, @LineParting, @ProductVSMarkingModel, 
                                     @NonconformanceDescriptionIfAny,@NonconformanceImage,@CreateCreator,@CreateTime);
                                    SELECT CAST(scope_identity() AS int);";

                        SqlParameter[] parameters = {
                            new SqlParameter("@OperatorName", SqlDbType.NVarChar, 50) { Value = LMSSIC.LMSSIC_OperatorName },
                            new SqlParameter("@ConfirmationTime", SqlDbType.DateTime) { Value = LMSSIC.LMSSIC_ConfirmationTime },
                            new SqlParameter("@LineParting", SqlDbType.NVarChar, 50) { Value = LMSSIC.LMSSIC_LineParting },
                            new SqlParameter("@ProductVSMarkingModel", SqlDbType.NVarChar, 50) { Value = LMSSIC.LMSSIC_ProductVSMarkingModel },
                            new SqlParameter("@NonconformanceDescriptionIfAny", SqlDbType.NVarChar, 200) { Value = (object)LMSSIC.LMSSIC_NonconformanceDescriptionIfAny ?? DBNull.Value },
                             new SqlParameter("@NonconformanceImage", SqlDbType.NVarChar, 500) { Value = (object)LMSSIC.LMSSIC_NonconformanceImage ?? DBNull.Value },
                             new SqlParameter("@CreateCreator", SqlDbType.NVarChar, 50) { Value = LMSSIC.LMSSC_CreateCreator },
                             new SqlParameter("@CreateTime", SqlDbType.DateTime) { Value = DateTime.Now }
                        };

                        using (var command = new SqlCommand(query, connection, transaction))
                        {
                            command.Parameters.AddRange(parameters);
                            var result = await command.ExecuteScalarAsync();
                            if (result != null)
                            {
                                transaction.Commit();
                                LMSSIC.LMSSIC_ID = Convert.ToInt32(result);
                                Logger.Info("新增成功");
                                RO.Status = HttpStatusCode.OK;
                                RO.Message = "OK";
                                RO.Data = LMSSIC;
                                return Request.CreateResponse(HttpStatusCode.OK, RO);
                            }
                            else
                            {
                                transaction.Rollback();
                                Logger.Error("插入记录失败");
                                RO.Status = HttpStatusCode.InternalServerError;
                                RO.Message = "Error";
                                RO.Data = null;
                                return Request.CreateResponse(HttpStatusCode.InternalServerError, RO);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        Logger.Warn("新增失败: " + ex.Message);
                        RO.Status = HttpStatusCode.InternalServerError;
                        RO.Message = "Error" + ex.Message;
                        RO.Data = null;
                        return Request.CreateResponse(HttpStatusCode.InternalServerError, RO);
                    }
                }
            }
        }
    }
}